// 引入pinia
import {
	defineStore,
} from 'pinia';
import {
	computed,
	reactive,
	ref,
} from 'vue';
// 通过 defineStore 创建的一个 store
// 将收货人地址信息存储
export const useaddressStore = defineStore('address', () => {
	const address = reactive(JSON.parse(uni.getStorageSync('address') || '{}'));
	const getaddress = (user) => {
		if (JSON.stringify(user) === '{}') {
			// 方法二：清空对象属性
			for (const key in address) {
				delete address[key];
			}
		}
		Object.assign(address, user);
		uni.setStorageSync('address', JSON.stringify(address));
	};
	// 收货详细地址的计算属性
	const addstr = computed(() => {
		if (!address.provinceName) {
			return '';
		}
		// 拼接 省，市，区，详细地址 的字符串并返回给用户
		return address.provinceName + address.cityName + address.countyName + address.detailInfo;
	});
	return {
		address,
		getaddress,
		addstr,
	};
});

// 将用户登录信息存储
export const useuserInfoStore = defineStore('userInfo', () => {
	const userInfo = reactive(JSON.parse(uni.getStorageSync('userInfo') || '{}'));
	const getuserInfo = (user) => {
		if (JSON.stringify(user) === '{}') {
			// 方法二：清空对象属性
			for (const key in userInfo) {
				delete userInfo[key];
			}
		}
		Object.assign(userInfo, user);
		uni.setStorageSync('userInfo', JSON.stringify(userInfo));
	};
	return {
		userInfo,
		getuserInfo,
	};
});

// 更新token
export const useupdatetokenStore = defineStore('updatetoken', () => {
	const token = ref(uni.getStorageSync('token') || '');
	const updatetoken = (t) => {
		token.value = t;
		uni.setStorageSync('token', JSON.stringify(token.value));
	};
	return {
		updatetoken,
		token,
	};
});

// 登录成功之后再返回之前的页面
export const usegobackpageStore = defineStore('gobackpage', () => {
	const backpage = reactive({});
	const gobackpage = (back) => {
		Object.assign(backpage, back);
		// uni.setStorageSync('token', JSON.stringify(token.value));
	};
	return {
		gobackpage,
		backpage,
	};
});
